package au.edu.utas.yu_qiao_group.luckyman.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import au.edu.utas.yu_qiao_group.luckyman.db.draws.DrawTable;
import au.edu.utas.yu_qiao_group.luckyman.db.raffles.RaffleTable;
import au.edu.utas.yu_qiao_group.luckyman.db.tickets.TicketTable;

public class Database {
  private static final String TAG = "LuckyManDB";

  private static final String DATABASE_NAME = "LuckyManDatabase";

  private static final int DATABASE_VERSION = 17;

  private SQLiteDatabase mDb;

  private DatabaseHelper mDbHelper;

  private final Context mCtx;

  public Database(Context ctx) {
    this.mCtx = ctx;
  }

  public SQLiteDatabase open() {
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return mDb;
  }

  public void close() {
    mDbHelper.close();
  }

  /**
   * DatabaseHelper class.
   * <p>
   * Database helper class to manage connections with the database.
   */
  private static class DatabaseHelper extends SQLiteOpenHelper {
    DatabaseHelper(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
      Log.d(TAG, "DatabaseHelper onCreate");
      db.execSQL(RaffleTable.CREATE_STATEMENT);
      db.execSQL(RaffleTable.CREATE_TRIGGER_STATEMENT);
      db.execSQL(DrawTable.CREATE_STATEMENT);
      db.execSQL(DrawTable.CREATE_TRIGGER_STATEMENT);
      db.execSQL(TicketTable.CREATE_STATEMENT);
      db.execSQL(TicketTable.CREATE_TRIGGER_STATEMENT);
    }

    //This code is called if the version number changes
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      Log.d(TAG, "DatabaseHelper onUpgrade");
      db.execSQL("DROP TABLE IF EXISTS " + RaffleTable.TABLE_NAME);
      db.execSQL("DROP TABLE IF EXISTS " + DrawTable.TABLE_NAME);
      db.execSQL("DROP TABLE IF EXISTS " + TicketTable.TABLE_NAME);
      onCreate(db);
    }
  }

}
